using System;
using System.Threading;
using Limestone.Storage.XML;
using NUnit.Framework;

namespace Limestone.Test
{
    [TestFixture]
    public class PageStubCacheFixture:TestBase
    {
        [SetUp]
        public void CleanUp()
        {
            try
            {
                ClearFolder(BasePagePath);
                ClearFolder(BaseTemplatePath);
                ClearFolder(BaseTrashcanPath);
            }
            catch (Exception)
            {
                Thread.Sleep(2000);
                ClearFolder(BasePagePath);
                ClearFolder(BaseTemplatePath);
                ClearFolder(BaseTrashcanPath);
            }
        }

        [Test]
        public void AddStub()
        {
            var getCurrentUserId = new GetCurrentUserFromFake("Henke");
            var storage = new XmlStorage(GetXmlCfg(), getCurrentUserId);
            var cache = new PageStubCache(storage);

            PopCache(cache);

            Assert.IsNotNull(cache.GetPageStub("/alpha.page"));
            Assert.IsNotNull(cache.GetPageStub("/beta.page"));
            Assert.IsNotNull(cache.GetPageStub("/alpha/gamma.page"));
            Assert.IsNotNull(cache.GetPageStub("/alpha/gamma/theta.page"));
        }

        [Test]
        public void RemoveStub()
        {
            var getCurrentUserId = new GetCurrentUserFromFake("Henke");
            var storage = new XmlStorage(GetXmlCfg(), getCurrentUserId);
            var cache = new PageStubCache(storage);

            PopCache(cache);

            cache.RemovePageStub("/alpha.page");

            Assert.IsNull(cache.GetPageStub("/alpha.page"));
            Assert.IsNull(cache.GetPageStub("/alpha/gamma.page"));
            Assert.IsNull(cache.GetPageStub("/alpha/gamma/theta.page"));
        }

        private static void PopCache(PageStubCache cache)
        {
            cache.AddPageStub(new PageStub("Alpha", "/alpha.page", "Alpha title", "/alphatemplate", false), "/");
            cache.AddPageStub(new PageStub("Beta", "/beta.page", "Beta title", "/betatemplate", false), "/");

            cache.AddPageStub(new PageStub("Gamma", "/alpha/gamma.page", "Gamma title", "/gammatemplate", false), "/alpha.page");

            cache.AddPageStub(new PageStub("Theta", "/alpha/gamma/theta.page", "Theta title", "/thetatemplate", false), "/alpha/gamma.page");
        }
    }
}